package com.geepi.base;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class DBUtil {
	private Connection mConnection;
	private Boolean isLocalMysql = true;
	public DBUtil() {
		
	}
	
	public boolean open() {
		String url = "";
		String username = "";
		String password = "";
		if (isLocalMysql == true) {
			url = "jdbc:mysql://localhost:3306/qixing";
			username = "root"; 
			password = "123456";
		} else {
//			String URL="jdbc:mysql://r.rdc.sae.sina.com.cn:3307/app_myappname";
			url = "jdbc:mysql://121.42.214.228:3306/qixing?characterEncoding=utf8"; 
			username = "root"; 
			password = "123456";
		}
		
		
		try {
			Class.forName("com.mysql.jdbc.Driver");
		} catch (ClassNotFoundException e) {
			// TODO: handle exception
			e.printStackTrace();
			return false;
		}
		
		try {
			mConnection = DriverManager.getConnection(url, username, password);
		    System.out.println("connect db...");	
		    if (mConnection == null) {
		    	return false;
		    }
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
//			String ss = e.getMessage();
			return false;
		}
		return true;
	}
	
	public ResultSet query(String sqlString) {
		String condition = sqlString;
		
		PreparedStatement objStatement;
		try {
			objStatement = mConnection.prepareStatement (condition);
			ResultSet rs = objStatement.executeQuery(); 
			return rs;
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
	
	public boolean update(String sqlString) {
		String condition = sqlString;
		PreparedStatement objStatement;
		  try{
	            objStatement = mConnection.prepareStatement(condition, Statement.RETURN_GENERATED_KEYS);  
	            objStatement.executeUpdate();
	            return true;
	        }catch(Exception e){
	            e.printStackTrace();
	        }
		  return false;
	}
	
}
